package com.ebelter.btcomlib.models.bluetooth.products.bloodoxgen;

import com.ebelter.btcomlib.utils.BaseHandle;

import com.ebelter.btcomlib.models.bluetooth.products.bloodoxgen.bean.BOMesureResultBean;
import com.ebelter.btcomlib.models.bluetooth.products.bloodoxgen.interfaces.BOMesureResult;

import com.ebelter.btcomlib.utils.BytesUtils;
import com.ebelter.btcomlib.utils.log.LogUtils;


public class BOBytesAnalysis extends BaseHandle {
    private static final String TAG = "BOBytesAnalysis";

    private BOMesureResult bOMesureResult;
    public void setBoMeasureCallback(BOMesureResult bOMesureResult) {
        this.bOMesureResult=bOMesureResult;
    }

    public void resultAnalysis(byte[] data) {

        if (bOMesureResult==null){
            LogUtils.i(TAG, "----bOMesureResult为空");
            return;
        }
        if (data == null || data.length < 3){
            return;
        }
        LogUtils.i(TAG, "----resultAnalysis-data = " + BytesUtils.bytes2HexStr(data));
        //检验数据
        if (!checkData(data)) {
            LogUtils.i(TAG, "----resultAnalysis-data = 校验码失败");
            return;
        }
        //解密后
        int cmdCode0 = data[0] & 0xff;
        int cmdCode1 = data[1] & 0xff;
        if (cmdCode0 != 0x55 || cmdCode1 != 0xaa) {
            return;
        }
        //业务码
        doResult(data);
    }


    private long lastReceiveTime;
    private void doResult(byte[] data) {



        final int bloodOxygen = data[3];
        int pulse = data[4];
        //正在测量
        if (pulse == 0) {
            post(new Runnable() {
                @Override
                public void run() {
                    bOMesureResult.mesureing(bloodOxygen);
                }
            });
            return;
        }

        long nowReceiveTime = System.currentTimeMillis();
        if (lastReceiveTime==nowReceiveTime){
            LogUtils.i(TAG,"时间相同--测量结果这次被屏蔽掉");
            return;
        }
        lastReceiveTime=nowReceiveTime;
        final BOMesureResultBean result = new BOMesureResultBean(bloodOxygen,pulse,nowReceiveTime);

        //测量结果回调
        post(new Runnable() {
            @Override
            public void run() {
                bOMesureResult.mesureResult(result);
            }
        });

    }

    private boolean checkData(byte[] data) {
        boolean isRealData = true;
        byte sum = 0;
        int count = data.length - 1;
        for (int i = 2; i < count; i++) {
            sum += data[i];
        }
        sum -= data[count];
        if (sum != 0) {
            isRealData = false;
        }
        return isRealData;
    }
}
